﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using System.Linq;
using System.Collections;
using Microsoft.SharePoint.WebControls;
using System.Data;

namespace PaulBeck.Timesheet.WebParts.Admin.AddProjectResource
{
    public partial class AddProjectResourceUserControl : UserControl
    {

        #region "Public Properties"

        public int ClientId
        {
            get
            {
                object o = ViewState["ClientId"];
                return (o == null) ? 0 : (int)o;
            }
            set
            {
                ViewState["ClientId"] = value;
            }
        }

        public int ProjectId
        {
            get
            {
                object o = ViewState["ProjectId"];
                return (o == null) ? 0 : (int)o;
            }
            set
            {
                ViewState["ProjectId"] = value;
            }
        }

        public string TimesheetAdminClientUrl
        {
            get
            {
                return CommonWFE.GetTimesheetAdminClientUrl();
            }
        }

        public string TimesheetAdminProjectUrl
        {
            get
            {
                return CommonWFE.GetTimesheetAdminProjectUrl();
            }
        }

        public string TimesheetAdminProjectResourceUrl
        {
            get
            {
                return CommonWFE.GetTimesheetAdminProjectResourceUrl();
            }
        }

        #endregion

        decimal billedHrs = 0;
        decimal estimatedHrs = 0;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                // Get the clients
                TSDBDataContext dc = new TSDBDataContext(BOL.Common.GetTimesheetConnectioninfo());
                var client = (from c in dc.Clients
                              select new
                              {
                                  c.ClientId,
                                  c.Name,
                                  c.Active,
                              });
                ddlClient.Items.Add(new ListItem("New", "0"));
                foreach (var item in client)
                {
                    if ((bool)item.Active)
                    {
                        ddlClient.Items.Add(new ListItem(item.Name, item.ClientId.ToString()));
                    }
                    else
                    {
                        ddlClient.Items.Add(new ListItem(item.Name + "(Inactive)", item.ClientId.ToString()));
                    }
                }
            }
            else
            {
                if (hiddenAction.Value != "")
                {
                    // Perform latest data refresh 
                    if (hiddenAction.Value == "ClientEdit")
                    {
                        Page.Response.Redirect(Page.Request.Url.AbsolutePath);
                    }
                    else if (hiddenAction.Value == "ClientAdd")
                    {
                        Page.Response.Redirect(Page.Request.Url.AbsolutePath);
                    }
                    else if (hiddenAction.Value == "ClientDelete")
                    {
                        Page.Response.Redirect(Page.Request.Url.AbsolutePath);
                    }
                    else if (hiddenAction.Value == "ProjectEdit")
                    {
                        Page.Response.Redirect(Page.Request.Url.AbsolutePath);
                    }
                    else if (hiddenAction.Value == "ProjectAdd")
                    {
                        Page.Response.Redirect(Page.Request.Url.AbsolutePath);
                    }
                    else if (hiddenAction.Value == "ProjectDelete")
                    {
                        Page.Response.Redirect(Page.Request.Url.AbsolutePath);
                    }
                    else if (hiddenAction.Value == "ResourceEdit")
                    {
                        ProjectChanged();
                    }
                    hiddenAction.Value = "";
                }
            }

        }

        protected void btnAssign_Click(object sender, EventArgs e)
        {

            int resourceId = 0;
            //    ArrayList al = pplResources.Accounts;
            PickerEntity entity;
            int count = this.pplResources.ResolvedEntities.Count;
            ArrayList list = new ArrayList();
            SPUser[] userArray = new SPUser[count];
            for (int i = 0; i < count; i++)
            {
                entity = (PickerEntity)this.pplResources.ResolvedEntities[i];
                // Remind admin user that current user must reside in the site collection with contribute privileges
                // Check if user exists in timesheetdb tbl Resources, if not add them
                TSDBDataContext dc = new TSDBDataContext(BOL.Common.GetTimesheetConnectioninfo());
                var resource = (from r in dc.Resources
                                where r.Name == entity.DisplayText
                              select new
                              {
                                r.Active,
                                r.ResourceId,
                              }).SingleOrDefault();

                if (resource == null)
                {
                    string displayName = entity.DisplayText;       
                    // Create the resource
                    Resource res = new Resource();
                    res.Name = displayName;
                    res.Active = true;
                    res.CreatedBy = CommonWFE.CurrentUserName();
                    res.CreatedDate = DateTime.Now;
                    res.UserId = entity.Key;
                    dc.Resources.InsertOnSubmit(res);
                    dc.SubmitChanges();
                    resourceId = (int)res.ResourceId;
                }
                else
                {
                    resourceId = resource.ResourceId;
                }
                // assign resource to project if it does not already exist
                var projresource = (from pr in dc.ProjectResources
                                    where pr.ProjectId == ProjectId
                                    && pr.ResourceId == resourceId
                                select new
                                {
                                    pr.ProjectResourceId
                                }).SingleOrDefault();
                if (projresource == null)
                {
                    // Insert a new record
                    ProjectResource pres = new ProjectResource();
                    pres.ProjectId = ProjectId;
                    pres.ResourceId = resourceId;
                    pres.CreatedBy = CommonWFE.CurrentUserName();
                    pres.CreatedDate = DateTime.Now;
                    dc.ProjectResources.InsertOnSubmit(pres);
                    dc.SubmitChanges();
                }
            }

            ProjectChanged();
            pplResources.Entities.Clear();
        }

        protected void ddlClient_SelectedIndexChanged(object sender, EventArgs e)
        {
            ClientId = Convert.ToInt32(ddlClient.SelectedValue);
            ClientChanged();
        }

        protected void ddlProject_SelectedIndexChanged(object sender, EventArgs e)
        {
            ProjectId = Convert.ToInt32(ddlProject.SelectedValue);
            ProjectChanged();
        }

        private void ClientChanged()
        {
            pplResources.Visible = false;
            btnAssign.Enabled = false;
            gvProjectResources.DataSource = null;
            gvProjectResources.DataBind();
            ProjectId = 0;  // ClientId has changed so remove the ProjectId

            TSDBDataContext dc = new TSDBDataContext(BOL.Common.GetTimesheetConnectioninfo());
            var projects = (from p in dc.Projects
                            where p.ClientId == ClientId
                            select new
                            {
                                p.ProjectId,
                                p.Description,
                                p.Active
                            });
            ddlProject.Items.Clear();
            ddlProject.Items.Add(new ListItem("New", "0"));
            foreach (var item in projects)
            {
                if ((bool)item.Active)
                {
                    ddlProject.Items.Add(new ListItem(item.Description, item.ProjectId.ToString()));
                }
                else
                {
                    ddlProject.Items.Add(new ListItem(item.Description + "(Inactive)", item.ProjectId.ToString()));
                }
            }
        }

        private void ProjectChanged()
        {
            pplResources.Visible = true;
            btnAssign.Enabled = true;
            TSDBDataContext dc = new TSDBDataContext(BOL.Common.GetTimesheetConnectioninfo());
            var projectResources = (from pr in dc.ProjectResources
                                    where pr.ProjectId == ProjectId
                                    select new
                                    {
                                        pr.ProjectResourceId,
                                        pr.Resource.Name,
                                        pr.TotalAllocatedHours,
                                        pr.TotalExpectedHours,
                                    });
            gvProjectResources.DataSource = projectResources;
            gvProjectResources.DataBind();
        }

        protected void gvProjectResources_RowDataBound(object sender, GridViewRowEventArgs e)
        {
           if (e.Row.RowType == DataControlRowType.DataRow)
           {
               // Get total hrs and add to billedHrs
               billedHrs = billedHrs + Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "TotalAllocatedHours").ToString());
               estimatedHrs = estimatedHrs + Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "TotalExpectedHours").ToString()); 
               // calc billed minus expected hrs to add a new row

           }
           else if (e.Row.RowType == DataControlRowType.Footer)
           {
               e.Row.Cells[0].Text = "Total: ";
               e.Row.Cells[1].Text = billedHrs.ToString();
               e.Row.Cells[2].Text = estimatedHrs.ToString();
               decimal outstandingHrs = estimatedHrs - billedHrs;
               e.Row.Cells[3].Text = outstandingHrs.ToString();
           }

        }



    }
}
